<template>
  <div class="app-container">
    <div class="filter-container">
      <!--<el-input disabled-->
      <!--@keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"-->
      <!--placeholder="请输入" v-model="listQuery.search"-->
      <!--&gt;-->
      <!--</el-input>-->
      <!--<el-button-->
      <!--disabled class="filter-item disabled" type="primary" v-waves icon="el-icon-search" @click="handleFilter"-->
      <!--&gt;-->
      <!--{{$t('table.search')}}-->
      <!--</el-button>-->
      <el-button
        class="filter-item" @click="handleCreate" type="success"
        icon="el-icon-plus"
      >新增
      </el-button>
    </div>

    <el-table stripe
      :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="加载中..." border fit
      highlight-current-row
      style="width: 100%"
    >
      <!--<el-table-column align="center" type="selection" width="55">-->
      <!--</el-table-column>-->
      <el-table-column align="center" label="数据库配置名称">
        <template slot-scope="scope">
          <span>{{scope.row.dbConfigName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="数据库IP">
        <template slot-scope="scope">
          <span>{{scope.row.dbHost}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名">
        <template slot-scope="scope">
          <span>{{scope.row.dbUsername | dataEncryption}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="密码">
        <template slot-scope="scope">
          <span>{{scope.row.dbPassword | dataEncryption}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="数据库端口">
        <template slot-scope="scope">
          <span>{{scope.row.dbPort}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="数据库实例名">
        <template slot-scope="scope">
          <span>{{scope.row.dbSid}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="数据库类型">
        <template slot-scope="scope">
          <span>{{formatDbType(scope.row.dbType)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="数据库字符集">
        <template slot-scope="scope">
          <span>{{formatCharset(scope.row.dbCharset)}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="启用状态">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{formatEnabled(scope.row.enabled)}}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column align="center" label="备注">
        <template slot-scope="scope">
          <span>{{scope.row.remark}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.actions')" width="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"
              class="el-icon-edit button-icon"></el-button>
          </el-tooltip>
          <!--<el-button-->
          <!--v-if="scope.row.status!='deleted'" size="mini" type="danger"-->
          <!--@click="handleDelete(scope.row)"-->
          <!--&gt;{{$t('table.delete')}}-->
          <!--</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageNum"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="130px"
        style='margin: 24px;'
      >
        <el-form-item label="数据库配置名称" prop="dbConfigName">
          <el-input v-model="temp.dbConfigName" type="text" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="数据库IP" prop="dbHost">
          <el-input v-model="temp.dbHost" type="text" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="dbUsername">
          <el-input v-model="temp.dbUsername" type="password" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="dbPassword">
          <el-input v-model="temp.dbPassword" type="password" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="数据库端口" prop="dbPort">
          <el-input v-model="temp.dbPort" type="number" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="数据库实例名" prop="dbSid">
          <el-input v-model="temp.dbSid" type="text" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="数据库类型" prop="dbType">
          <el-select v-model="temp.dbType" type="text" placeholder="请选择">
            <el-option :value="1" label="Oracle"></el-option>
            <el-option :value="2" label="mysql"></el-option>
            <!--<el-option :value="3" label="sqlserver"></el-option>-->
          </el-select>
        </el-form-item>
        <el-form-item label="数据库字符集" prop="dbCharset">
          <el-select v-model="temp.dbCharset" type="text" placeholder="请选择">
            <el-option :value="0" label="utf-8"></el-option>
            <el-option :value="1" label="gbk"></el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="启用状态" prop="enabled">-->
        <!--<el-select v-model="temp.enabled" type="text" placeholder="请选择">-->
        <!--<el-option :value="0" label="启用"></el-option>-->
        <!--<el-option :value="1" label="禁用"></el-option>-->
        <!--</el-select>-->
        <!--</el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark" type="text" placeholder="请输入">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button :loading="testLoading" type="warning" @click="testData">测试{{testLoading?'中..':''}}</el-button>
        <el-button :disabled="!testPass" v-if="dialogStatus=='create'" type="primary"
          @click="createData">{{$t('table.confirm')}}
        </el-button>
        <el-button :disabled="!testPass" v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { databaseList, databaseAdd, databaseTest, databaseTestAdd, databasePut, databaseDelete } from '@/api/data'
  import waves from '@/directive/waves' // 水波纹指令
  import { parseTime } from '@/utils'
  import pinyin from 'pinyin'

  export default {
    name: 'complexTable',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 20,
          search: undefined
        },
        showReviewer: false,
        temp: {
          dataStatus: 0,
          dbConfigName: '',
          dbHost: '',
          dbPassword: '',
          dbPort: '',
          dbSid: '',
          dbType: 1,
          dbCharset: 0,
          dbUsername: '',
          enabled: 1,
          id: '',
          remark: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          dbConfigName: [{ required: true, message: '请输入...', trigger: 'change' }],
          dbHost: [{
            required: true,
            pattern: /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/,
            message: '请输入正确的IP地址',
            trigger: 'change'
          }],
          dbUsername: [{ type: 'string', required: true, message: '请输入...', trigger: 'change' }],
          dbPassword: [{ type: 'string', required: true, message: '请输入...', trigger: 'change' }],
          dbSid: [{ required: true, message: '请输入...', trigger: 'change' }],
          dbPort: [{ max: 5, required: true, message: '请输入正确的端口号', trigger: 'change' }],
          dbType: [{ required: true, message: '请选择...', trigger: 'change' }],
          dbCharset: [{ required: true, message: '请选择...', trigger: 'change' }],
          enabled: [{ required: true, message: '请选择...', trigger: 'change' }],
        },
        downloadLoading: false,
        testPass: false,
        testLoading: false
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        // return calendarTypeKeyValue[type]
      },
      dataEncryption(msg){
        return String(msg).replace(/./g,"*")
      }
    },
    created() {
      this.getList()
    },
    mounted() {
      this.$watch(
        function() {
          return JSON.stringify(this.temp)
        },
        function() {
          this.testPass = false
        }
      )
    },
    methods: {
      formatDbType(data) {
        switch (data) {
          case 1:
            return 'Oracle'
          case 2:
            return 'mysql'
          case 3:
            return 'sqlserver'
        }
      },
      formatEnabled(data) {
        switch (data) {
          case 0:
            return '启用中'
          case 1:
            return '禁用中'
        }
      },
      formatCharset(data) {
        switch (data) {
          case 0:
            return 'utf-8'
          case 1:
            return 'gbk'
        }
      },
      getList() {
        this.listLoading = true
        databaseList(this.listQuery).then(response => {
          // console.log(response)
          this.listLoading = false
          this.list = response.Data
          this.total = parseInt(response.total)
          console.log(response)
        })
      },
      handleFilter() {
        this.listQuery.pageNum = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      resetTemp() {
        this.temp = {
          attitude: null,
          author: '',
          content: '',
          dataStatus: null,
          fromAttr: '',
          id: '',
          isOriginal: null,
          newsClassId: '',
          online: null,
          summary: '',
          title: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      testData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.testLoading = true;
            if(this.dialogStatus === 'create'){
              databaseTestAdd(this.temp).then(() => {
                this.testLoading = false
                this.testPass = true
                this.$notify({
                  title: '成功',
                  duration: 5000,
                  message: '测试通过',
                  type: 'success'
                })
              }).catch(() => {
                this.testLoading = false
                this.testPass = false
                this.$notify({
                  title: '失败',
                  duration: 5000,
                  type: 'error',
                  message: '测试未通过，请检查配置'
                })
              })
            };
            if(this.dialogStatus === 'update'){
              databaseTest(this.temp).then(() => {
                this.testLoading = false
                this.testPass = true
                this.$notify({
                  title: '成功',
                  duration: 5000,
                  message: '测试通过',
                  type: 'success'
                })
              }).catch(() => {
                this.testLoading = false
                this.testPass = false
                this.$notify({
                  title: '失败',
                  duration: 5000,
                  type: 'error',
                  message: '测试未通过，请检查配置'
                })
              })
            };
          }
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid && this.testPass) {
            databaseAdd(this.temp).then(() => {
              this.getList()
              this.testPass = false
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 5000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid && this.testPass) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            databasePut(tempData).then(() => {
              this.getList()
              this.testPass = false
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 5000
              })
            })
          }
        })
      },
      handleDelete(row) {
        this.$confirm('确认删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          databaseDelete(row).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })

      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
